package com.turbo.action;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataKey;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.util.Optional;

public class PsiAction extends AnAction {
    @Override
    public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
        Project project = anActionEvent.getProject();

        // 找到类，添加一些属性
        WriteCommandAction.runWriteCommandAction(project, new Runnable() {
            @Override
            public void run() {
                PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
                PsiClass testFc = JavaPsiFacade.getInstance(project).findClass("pool.turbo.test.TestFc", GlobalSearchScope.projectScope(project));
                PsiField field = elementFactory.createFieldFromText("public static final String TEST = \"TEST\";", null);
                testFc.add(field);
                /*PsiField[] fields = testFc.getFields();
                for (PsiField psiField : fields) {
                    psiField.delete();
                }*/
            }
        });
    }


    @Override
    public void update(@NotNull AnActionEvent anActionEvent) {
        PsiFile psiFile = anActionEvent.getData(PlatformDataKeys.PSI_FILE);
        FileType fileType = psiFile.getFileType();
        anActionEvent.getPresentation().setEnabled("java".equals(fileType.getDefaultExtension()));
    }
}
